<template>
  <!-- 条码列表 -->
  <div class="barcode" @click.stop="materialVis=false">
    <jc-button
      v-if="msg!==1"
      :btn-arr="['reload', 'pass', 'sub', 'option', 'remove', 'newy']"
      :disab-arr="['copy', 'close', 'cancel', 'com2', 'chart', 'freeze']"
      @newly="newly"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @forbidden="using(1)"
      @startUsing="using(2)"
      @handleCom1="handleCom"
      @del="delet"
      @refresh="handleGetUntreated"
      @toExcel="handleExport"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          v-if="msg!==1"
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div>
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        @selectionChange="handleSelectAll"
        @clickRow="warehouseSelectRow"
      >
        <!--仓库编号-->
        <template v-slot:btnStates="col">
          <el-link type="primary" @click="detailPurchase(col.scope.row)">{{ col.scope.row.fnumber }}</el-link>
        </template>
        <!--物料编号-->
        <template v-slot:billSlot="col">
          <el-link type="primary" @click="jumpMateriel1(col.scope.row.materialfnumber)">{{ col.scope.row.materialfnumber }}</el-link>
        </template>
        <!--        审核状态-->
        <template v-slot:btnState="col">
          <el-tag :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
        </template>
        <!--        禁用状态-->
        <template v-slot:tagSlot="col">
          <el-tag v-if="col.scope.row.fforbidstatus === 'A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else type="danger">{{ $t('btn.disab') }}<!--禁用--></el-tag>
        </template>
      </jc-table>
      <cardTab :tab-arr="tabArr" field="materialfname" @search="handleQueryBomList" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <!-- 新增|修改 -->
    <el-dialog
      v-dialogDrag
      :title="stockTitle"
      model
      :visible.sync="isStockDialog"
      :close-on-click-modal="false"
      width="500px"
      :before-close="handleClose"
    >
      <el-form ref="purchaseRef" :model="prodValue" label-width="100px" :disabled="isDisabled">
        <el-form-item :label="$t('shop.fnumber')">
          <el-input v-model.trim="prodValue.fnumber" size="mini" disabled />
        </el-form-item>
        <el-form-item :label="$t('market.stockname1')" prop="fpaezCombo">
          <el-input v-model.trim="prodValue.positionfname" size="mini">
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="isPositions=true"
            />
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('shop.fnumber1')">
          <el-input
            v-model.trim="prodValue.materialfnumber"
            size="mini"
            @input="getAtuo(prodValue.materialfnumber)"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="isMateria=true"
            />
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('shop.fname2')">
          <el-input v-model.trim="prodValue.materialfname" size="mini" disabled />
        </el-form-item>
        <el-form-item :label="$t('shop.fspecificaTion')">
          <el-input v-model.trim="prodValue.fspecification" size="mini" disabled />
        </el-form-item>
        <el-form-item :label="$t('shop.fdescripTion')">
          <el-input v-model.trim="prodValue.fdescription" size="mini" disabled />
        </el-form-item>
      </el-form>
      <div v-if="materialVis" class="tabPosit">
        <number-code :fnumber="fnumber" @material="materialData" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isStockDialog=false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="addStock">{{ $t('btn.save') }}</el-button>
      </div>
    </el-dialog>
    <!--    物料弹窗-->
    <material v-if="isMateria" @material="materialData" />
    <positions v-if="isPositions" @client="positionData" />
  </div>
</template>

<script>
import {
  queryTBdCodeList,
  insertCode, updateCode,
  submitWmsCode, notsubmitWmsCode,
  deleteCode, notreviewWmsCode,
  reviewWmsCode, ableWmsCode, disableWmsCode
} from '@/api/wms/stock'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import jcButton from '@/components/Button'
import positions from '@/views/wms/barcode/component/positions'
export default {
  // name: 'ForthwithRep',
  components: {
    positions,
    cardTab: () => import('@/components/cardTab'),
    numberCode: () => import('@/components/NumberCode'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    msg: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      materialVis: false,
      fnumber: '',
      isMateria: false, // 物料
      isPositions: false, // 仓位
      isStockDialog: false, // 新增
      isDisabled: false, // 禁用
      stockTitle: '',
      ftype: 80,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      tabArr: [
        { label: '餐台', name: '餐台' },
        { label: '餐椅', name: '餐椅' },
        { label: '包装', name: '包装' },
        { label: '管材', name: '管材' },
        { label: '五金', name: '五金' },
        { label: '泡沫', name: '泡沫' },
        { label: '海绵', name: '海绵' },
        { label: '纸箱', name: '纸箱' },
        { label: '纸平卡', name: '纸平卡' },
        { label: '布', name: '布' },
        { label: '皮', name: '皮' },
        { label: '软体', name: '软体' },
        { label: '底盘', name: '底盘' },
        { label: '螺丝', name: '螺丝' }
      ],
      // 表头
      tableData: [], // 销售数据
      tableHeight: '73vh',
      tableHeader: [
        { label: this.$t('market.barcode'), type: 'states', prop: 'fnumber', width: '120' },
        { label: this.$t('market.stockname1'), prop: 'positionfname', width: '150' },
        { label: this.$t('market.stockNumber1'), prop: 'positionfnumber', width: '120' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus', width: '100' },
        { label: this.$t('market.forbidStatu'), type: 'tag', prop: 'fforbidstatus', width: '100' },
        { label: this.$t('shop.fnumber1'), type: 'bill', prop: 'materialfnumber', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'materialfname', width: '150' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecification' },
        { label: this.$t('shop.fdescripTion'), prop: 'fdescription' },
        { label: this.$t('market.stockUnit'), prop: 'unit', width: '100' },
        { label: this.$t('market.stockQty'), prop: 'fqty', width: '100' },
        { label: this.$t('market.creator'), prop: 'fcreator', width: '100' },
        { label: this.$t('market.createDate'), prop: 'fcreatedate', width: '100' }
      ],
      tableHeader1: [],
      billtypes: [], // 仓库类型
      prodValue: {}
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 240px)' : '70vh'
  },
  methods: {
    // 输入物料编码
    getAtuo(fnumber) {
      this.materialVis = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 新增
    newly() {
      this.prodValue = {
        fpositionid: '',
        fmaterialid: '',
        materialfnumber: '',
        fdescription: '',
        materialfname: '',
        positionfname: ''
      }
      this.isDisabled = false
      this.isStockDialog = true
      this.stockTitle = '新增条码'
    },
    // 修改
    detailPurchase(ev) {
      this.isDisabled = ev.fdocumentstatus === this.$t('market.state1') || ev.fdocumentstatus === this.$t('market.state2')
      this.prodValue = { ...ev }
      this.isStockDialog = true
      this.stockTitle = '条码详情'
      this.billtypes.length === 0 && this.queryTBasBilltype() // 仓库类型
    },
    // 新增 修改仓库
    addStock() {
      const DATA = {
        ...notoMxBmina(this.prodValue)
      }
      const api = this.prodValue.fid ? updateCode : insertCode
      api(DATA).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
          this.isStockDialog = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryTBdCodeList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                if (item.fforbidstatus === 'A') {
                  item.fforbidstatus = '正常'
                } else {
                  item.fforbidstatus = '禁用'
                }
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '条码列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取条码
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await queryTBdCodeList(DATA)
      this.tableData = RES.data.list
      this.tableData.map(item => {
        return toMxBmina(item)
      })
      this.total = RES.data.total
      this.loading = false
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList(ev) {
      this.searCollData = []
      this.currentPage = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 物料
    materialData(item) {
      if (item.fmaterialId) {
        this.prodValue.fmaterialid = item.fmaterialId
        this.prodValue.materialfnumber = item.fnumber
        this.prodValue.materialfname = item.fname
        this.prodValue.fmodel = item.fname
        this.prodValue.fspecification = item.fspecificaTion
        this.prodValue.fdescription = item.fdescripTion
      }
      this.isMateria = false
    },
    // 仓位
    positionData(item) {
      if (item.fid) {
        this.prodValue.fpositionid = item.fid
        this.prodValue.positionfname = item.fname
      }
      this.isPositions = false
    },
    // 选中
    handleSelectAll(val) {
      this.val = val
      this.selectVal = []
      this.entryData = []
      val.forEach(item => {
        this.entryData.push(item.fid)
        item.fnumber && this.selectVal.push(item.fnumber)
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? submitWmsCode : notsubmitWmsCode
      this.toExamineFun(api)
    },
    // 审核
    async audit(ev) {
      const api = ev === 1 ? reviewWmsCode : notreviewWmsCode
      this.toExamineFun(api)
    },
    // 禁用启用
    async using(ev) {
      const api = ev === 1 ? disableWmsCode : ableWmsCode
      this.toExamineFun(api)
    },
    // 删除
    delet() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = deleteCode
        this.toExamineFun(api)
      })
    },
    // 套打打印
    handleCom() {
      const FNUMBER = this.entryData.join(',')
      this.$router.push({ path: `/barcodeTong/${FNUMBER}` })
    },
    // 向父传参
    warehouseSelectRow(ev) {
      this.$emit('client', ev)
    },
    handleClose() {
      this.prodValue = {}
      this.isStockDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.barcode {
  @include listBom;
  position: relative;
  .el-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  .tabPosit {
    position: absolute;
    top: 210px;
  }
  .header{
    position:relative;
    margin-bottom: 5px;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
